<script setup>
import api from '../api/attraction_api.js'  // 注意修改API路径为attraction相关接口
import { ref, onMounted } from "vue";
import { ElMessageBox } from "element-plus";
import lodash from 'lodash'
import loginApi from '../api/login_api.js'
import favoritesApi from '../api/favorites_api.js'
import reviewApi from '../api/review_api.js' // 导入评论API

// 数据定义区域
const tableData = ref([]);
const total = ref(0);
const editWinVisible = ref(false);
const reviewWinVisible = ref(false); // 评论窗口
const currentAttraction = ref({}); // 当前评论的景点

// 当前登录用户信息
const loginUser = ref({
  role: localStorage.getItem("role") || "admin", // 默认为admin，实际应该从登录信息中获取
  id: localStorage.getItem("userId") || null
});

const searchObj = ref({
  current: 1,
  limit: 10,
  name: '',
  city: '',
  type: ''
});

const obj = ref({});
const reviewObj = ref({}); // 评论对象

// 查询方法
const search = async () => {
  const result = await api.page(searchObj.value);
  tableData.value = result.data;
  total.value = result.count;
};

onMounted(async () => {
  await search();
});

const editCancel = () => {
  obj.value = {};
  editWinVisible.value = false;
};

const editCommit = async () => {
  if (obj.value.id) {
    await api.edit(obj.value);
  } else {
    await api.add(obj.value);
  }
  search();
  editWinVisible.value = false;
};

const handleSearch = () => {
  searchObj.value.current = 1;
  search();
};

const handleSizeChange = (val) => {
  searchObj.value.limit = val;
  search();
};

const handleCurrentChange = (val) => {
  searchObj.value.current = val;
  search();
};

const handleAdd = () => {
  obj.value = {
    name: '',
    city: '',
    type: '',
    description: '',
    latitude: '',
    longitude: ''
  };
  editWinVisible.value = true;
};

const handleEdit = (index, row) => {
  obj.value = lodash.clone(row);
  editWinVisible.value = true;
  console.log(index, row);
};

const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该景点吗？',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error'
      }
  )
      .then(async () => {
        await api.del(row.id);
        searchObj.value.current = 1;
        search();
      })
      .catch(() => {

      });
};

// 收藏功能
const handleFavorite = async (row) => {
  try {
    // 获取当前登录用户的信息
    const userInfo = await loginApi.userinfo();

    if (!userInfo || !userInfo.id) {
      ElMessageBox.alert('请先登录', '提示', { type: 'warning' });
      return;
    }

    // 构造收藏数据
    const favoriteData = {
      user_id: userInfo.id,
      attraction_id: row.id,
      is_deleted: 0
    };

    // 调用收藏接口
    await favoritesApi.add(favoriteData);

    ElMessageBox.alert('收藏成功', '提示', { type: 'success' });
  } catch (error) {
    console.error('收藏失败:', error);
    ElMessageBox.alert('收藏失败: ' + (error.message || '未知错误'), '提示', { type: 'error' });
  }
};

// 评论功能
const handleReview = async (row) => {
  try {
    // 获取当前登录用户的信息
    const userInfo = await loginApi.userinfo();

    if (!userInfo || !userInfo.id) {
      ElMessageBox.alert('请先登录', '提示', { type: 'warning' });
      return;
    }

    // 设置当前评论的景点
    currentAttraction.value = row;

    // 初始化评论对象
    reviewObj.value = {
      user_id: userInfo.id,
      attraction_id: row.id,
      rating: 5, // 默认评分5星
      comment: ''
    };

    // 显示评论窗口
    reviewWinVisible.value = true;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessageBox.alert('获取用户信息失败: ' + (error.message || '未知错误'), '提示', { type: 'error' });
  }
};

// 提交评论
const submitReview = async () => {
  try {
    // 验证评论内容
    if (!reviewObj.value.comment || reviewObj.value.comment.trim() === '') {
      ElMessageBox.alert('请输入评论内容', '提示', { type: 'warning' });
      return;
    }

    // 验证评分
    if (!reviewObj.value.rating || reviewObj.value.rating < 1 || reviewObj.value.rating > 5) {
      ElMessageBox.alert('请选择有效的评分(1-5星)', '提示', { type: 'warning' });
      return;
    }

    // 调用评论接口
    await reviewApi.add(reviewObj.value);

    ElMessageBox.alert('评论成功', '提示', { type: 'success' });
    reviewWinVisible.value = false;
  } catch (error) {
    console.error('评论失败:', error);
    ElMessageBox.alert('评论失败: ' + (error.message || '未知错误'), '提示', { type: 'error' });
  }
};

// 取消评论
const cancelReview = () => {
  reviewObj.value = {};
  reviewWinVisible.value = false;
};

const isAdminLogin = () => {
  return loginUser.value.role === 'admin';
}
</script>

<template>
  <div class="attraction-management-container">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchObj" style="margin-top: 10px; margin-bottom: 15px;">
      <el-form-item label="景点名称">
        <el-input v-model="searchObj.name" placeholder="请输入景点名称" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item label="所在城市">
        <el-input v-model="searchObj.city" placeholder="请输入城市" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item label="景点类型">
        <el-input v-model="searchObj.type" placeholder="请输入类型" clearable style="width: 200px;" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
      <el-form-item v-if="isAdminLogin()">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <!-- 景点表格 -->
    <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px;"
        border
        stripe
        :header-cell-style="{ 'background-color': '#f5f7fa', 'font-weight': 'bold' }"
    >
      <!--      <el-table-column label="ID" width="80" align="center">-->
      <!--        <template #default="scope">-->
      <!--          {{ scope.row.id }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="景点名称" min-width="150">
        <template #default="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="城市" min-width="120">
        <template #default="scope">
          {{ scope.row.city }}
        </template>
      </el-table-column>
      <el-table-column label="类型" min-width="120">
        <template #default="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>
      <el-table-column label="经纬度" min-width="200">
        <template #default="scope">
          <div>纬度: {{ scope.row.latitude }}</div>
          <div>经度: {{ scope.row.longitude }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180" align="center">
        <template #default="scope">
          <div v-if="isAdminLogin()">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"                style="margin-left: 5px;"
            >
              删除
            </el-button>
          </div>
          <div v-else>
            <el-button
                size="small"
                type="primary"
                @click="handleFavorite(scope.row)"
                style="margin-right: 5px;"
            >
              收藏
            </el-button>
            <el-button
                size="small"
                type="success"
                @click="handleReview(scope.row)"
            >
              评论
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 30, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="text-align: right; margin-top: 10px;"
    />

    <!-- 编辑/新增对话框 -->
    <el-dialog v-model="editWinVisible" title="编辑景点信息" width="600px">
      <el-form :model="obj" label-width="100px">
        <el-form-item label="ID" v-if="obj.id">
          <el-input v-model="obj.id" disabled />
        </el-form-item>
        <el-form-item label="景点名称">
          <el-input v-model="obj.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="城市">
          <el-input v-model="obj.city" autocomplete="off" />
        </el-form-item>
        <el-form-item label="类型">
          <el-input v-model="obj.type" autocomplete="off" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" v-model="obj.description" autocomplete="off" />
        </el-form-item>
        <el-form-item label="纬度">
          <el-input v-model="obj.latitude" autocomplete="off" />
        </el-form-item>
        <el-form-item label="经度">
          <el-input v-model="obj.longitude" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 评论对话框 -->
    <el-dialog v-model="reviewWinVisible" title="发表评论" width="500px">
      <el-form :model="reviewObj" label-width="80px">
        <el-form-item label="景点">
          <el-input v-model="currentAttraction.name" disabled />
        </el-form-item>
        <el-form-item label="评分" required>
          <el-rate
            v-model="reviewObj.rating"
            :max="5"
            :allow-half="false"
            show-score
            score-template="{value}星"
          />
        </el-form-item>
        <el-form-item label="评论内容" required>
          <el-input
            type="textarea"
            v-model="reviewObj.comment"
            autocomplete="off"
            rows="4"
            placeholder="请输入您的评论..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelReview">取消</el-button>
          <el-button type="primary" @click="submitReview">提交评论</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
